﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.Contract.ContractForeEnd;
using HamcoWcs.DAL;
using HamcoWcs.Models.ForeEndModels.DeviceDetails;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HamcoWcs.Service.Common;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Contract.ContractPcon;
using HamcoWcs.Contract.ContractSrm;
using HamcoWcs.Models.DeviceMsgs;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using HamcoWcs.Models.DeviceMsgs.SrmMsgs;
using HamcoWcs.Models.Common;

namespace HamcoWcs.Service.ForeEnd
{
    [AutoInject(typeof(IForeEndGetDataService), InjectType.Scope)]
    public class ForeEndGetDataService : ForeEndBaseService, IForeEndGetDataService
    {
        public static JsonSerializerSettings jsonSetting = new JsonSerializerSettings()
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        private readonly IPconBaseService _pconBaseService;
        private readonly IBaseSrmTaskService _baseSrmTaskService;
        public ForeEndGetDataService(IPconBaseService pconBaseService, IBaseSrmTaskService baseSrmTaskService, WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger) : base(wcsDbContext, mapper, logger)
        {
            _pconBaseService = pconBaseService;
            _baseSrmTaskService = baseSrmTaskService;
        }

        public ForeEndResult GetDeviceData(string deviceName)
        {
            //throw new NotImplementedException();
                string msg = "";
                if (deviceName.Contains("con"))
                {
                    try
                    {
                        var tpconName = deviceName.Replace("con", "");
                        int pconName = int.Parse(tpconName);
                        var plcs = _pconBaseService.GetAllPconPlcs();
                        var plcinfo = plcs.FirstOrDefault(d => d.Pcons.ContainsKey(pconName));
                        var pcon = plcinfo.Pcons[pconName];
                        var recvmsg = _mapper.Map<PconRecvMsg>(pcon);
                        msg = JsonConvert.SerializeObject(recvmsg, jsonSetting);
                    }
                    catch (Exception)
                    {
                        throw new Exception($"获取{deviceName}信息异常");
                    }
                }
                else if (deviceName.Contains("srm"))
                {
                    deviceName = deviceName.ToLower().FirstUpper();
                    var plc = _baseSrmTaskService.GetSrmPlc(deviceName);
                    var recvmsg = _mapper.Map<SrmRecvMsg>(plc);
                    msg = JsonConvert.SerializeObject(recvmsg, jsonSetting);
                }

                return new ForeEndResult(msg);

        }
    }
}
